package ar.edu.itba.it.cg.grupo01.impl.shape;

import java.awt.Color;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;

import ar.edu.itba.it.cg.grupo01.api.Intersection;
import ar.edu.itba.it.cg.grupo01.api.Ray;
import ar.edu.itba.it.cg.grupo01.api.shape.Shape;
import ar.edu.itba.it.cg.grupo01.impl.IntersectionFactory;
import ar.edu.itba.it.cg.grupo01.impl.Utilities;

public class Rectangle extends AbstractShape {
	
	private Point3d p;
	private Point3d q;
	private Point3d r1;
	private Point3d r2;
	
	private CompositeShape rectangle;

	public Rectangle(final Point3d a, final Point3d b, final Point3d c,
			IntersectionFactory intersectionFactory) {
		this(a, b, c, intersectionFactory, null);
	}
	
	public Rectangle(final Point3d a, final Point3d b, final Point3d c,
			IntersectionFactory intersectionFactory, Color color) {
		super(intersectionFactory);
		
		List<Point3d> points = Utilities.pointsFormRightTriangle(a, b, c);
		
		if (points == null) {
			throw new RuntimeException("Specified points do not describe a rectangle");
		}
		
		this.r1 = points.get(0);
		this.p = points.get(1);
		this.q = points.get(2);
		
		Vector3d v = new Vector3d(this.p);
		v.sub(this.r1);
		
		this.r2 = new Point3d(this.q);
		this.r2.add(v);
		
		Set<Triangle> triangles = new HashSet<Triangle>();
		Triangle t1 = new Triangle(this.p, this.q, this.r1, intersectionFactory);
		Triangle t2 = new Triangle(this.p, this.q, this.r2, intersectionFactory);
		triangles.add(t1);
		triangles.add(t2);
		
		this.rectangle = new CompositeShape(triangles, intersectionFactory);
	}

	@Override
	public Intersection<? extends Shape> intersects(Ray ray) {
		
		return this.rectangle.intersects(ray);
	}

}
